// 获取相关 CSS 属性
function getCss(o: HTMLElement, key: string) {
  if (document.defaultView && document.defaultView.getComputedStyle) {
    return document.defaultView.getComputedStyle(o, null)[key as any] as any;
  } else {
    return '';
  }
}

interface Params {
  left: number;
  top: number;
  currentX: number;
  currentY: number;
  flag: boolean;
}

const params: Params = {
  left: 0,
  top: 0,
  currentX: 0,
  currentY: 0,
  flag: false,
};

function startDrag(
  bar: HTMLElement,
  target: HTMLElement,
  callback?: (x: number, y: number) => void,
) {
  // body 当前宽度
  const screenWidth = document.body.clientWidth;
  // 可见区域高度
  const screenHeight = document.documentElement.clientHeight;

  // 对话框宽度
  const dragDomW = target.offsetWidth;
  // 对话框高度;
  const dragDomH = target.offsetHeight;

  const minDomLeft = target.offsetLeft;
  const minDomTop = target.offsetTop;

  const maxDragDomLeft = screenWidth - minDomLeft - dragDomW;
  const maxDragDomTop = screenHeight - minDomTop - dragDomH;

  if (getCss(target, 'left') !== 'auto') {
    params.left = getCss(target, 'left');
  }
  if (getCss(target, 'top') !== 'auto') {
    params.top = getCss(target, 'top');
  }

  // o 是移动对象
  bar.onmousedown = function (event: MouseEvent) {
    params.flag = true;
    if (!event) {
      event = window.event as MouseEvent;
      // 防止 IE 文字选中
      bar.onselectstart = function () {
        return false;
      };
    }
    const e = event;
    params.currentX = e.clientX;
    params.currentY = e.clientY;
  };

  document.onmouseup = function () {
    params.flag = false;
    if (getCss(target, 'left') !== 'auto') {
      params.left = getCss(target, 'left');
    }
    if (getCss(target, 'top') !== 'auto') {
      params.top = getCss(target, 'top');
    }
  };

  document.onmousemove = function (event) {
    const e: any = event || window.event;
    if (params.flag) {
      const nowX = e.clientX;
      const nowY = e.clientY;
      const disX = nowX - params.currentX;
      const disY = nowY - params.currentY;

      let left = Number.parseInt(String(params.left)) + disX;
      let top = Number.parseInt(String(params.top)) + disY;

      // 拖出屏幕边缘
      if (-left > minDomLeft) {
        left = -minDomLeft;
      } else if (left > maxDragDomLeft) {
        left = maxDragDomLeft;
      }

      if (-top > minDomTop) {
        top = -minDomTop;
      } else if (top > maxDragDomTop) {
        top = maxDragDomTop;
      }

      target.style.left = `${left}px`;
      target.style.top = `${top}px`;

      if (typeof callback == 'function') {
        callback((Number.parseInt(String(params.left)) || 0) + disX, (Number.parseInt(String(params.top)) || 0) + disY);
      }

      if (event.preventDefault) {
        event.preventDefault();
      }
      return false;
    }
  };
}

export default startDrag;
